import { describe, it, expect } from 'vitest'
import fc from 'fast-check'
import { generateImagePrompt, type EmotionItem, analyzeEmotion } from './emotionAnalysis.js'
import { APIError } from '../middleware/error.js'

describe('Emotion Analysis Service', () => {
  // **Feature: emotion-3d-website, Property 8: Image Prompt Derivation**
  // **Validates: Requirements 4.1**
  it('should generate image prompts containing emotion keywords', () => {
    fc.assert(
      fc.property(
        fc.array(
          fc.record({
            name: fc.constantFrom('happy', 'sad', 'anxious', 'calm', 'angry', 'excited', 'confused', 'hopeful'),
            intensity: fc.integer({ min: 0, max: 100 }),
            color: fc.hexaString({ minLength: 7, maxLength: 7 }).map(s => '#' + s),
            icon: fc.string({ minLength: 1, maxLength: 2 }),
          }),
          { minLength: 1, maxLength: 8 }
        ),
        fc.string({ minLength: 10, maxLength: 200 }),
        (emotions: EmotionItem[], summary: string) => {
          const prompt = generateImagePrompt(emotions, summary)
          
          // Get top 3 emotions by intensity
          const topEmotions = [...emotions]
            .sort((a, b) => b.intensity - a.intensity)
            .slice(0, 3)
          
          // Check that prompt contains at least one emotion keyword
          const containsEmotionKeyword = topEmotions.some(emotion => 
            prompt.toLowerCase().includes(emotion.name.toLowerCase())
          )
          
          return containsEmotionKeyword && prompt.length > 0
        }
      ),
      { numRuns: 100 }
    )
  })

  // **Feature: emotion-3d-website, Property 7: API Error Handling**
  // **Validates: Requirements 3.5**
  it('should return APIError with proper structure for any error', () => {
    // Property test: For any error scenario, APIError should have required fields
    fc.assert(
      fc.property(
        fc.record({
          message: fc.string({ minLength: 1, maxLength: 100 }),
          statusCode: fc.integer({ min: 400, max: 599 }),
          retryable: fc.boolean(),
        }),
        (errorData) => {
          const error = new APIError(errorData.message, errorData.statusCode, errorData.retryable)
          
          // Verify APIError structure
          const hasMessage = typeof error.message === 'string' && error.message.length > 0
          const hasStatusCode = typeof error.statusCode === 'number' && error.statusCode >= 400
          const hasRetryable = typeof error.retryable === 'boolean'
          const isAPIError = error instanceof APIError
          
          return isAPIError && hasMessage && hasStatusCode && hasRetryable
        }
      ),
      { numRuns: 100 }
    )
  })
})
